<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库与系统监控仪表盘</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }

        .header h1 {
            margin: 0;
            color: #2c3e50;
        }

        .refresh-controls {
            display: flex;
            align-items: center;
        }

        .refresh-interval {
            margin-right: 10px;
        }

        .dashboard-section {
            margin-bottom: 25px;
        }

        .dashboard-section h2 {
            margin: 0 0 15px 0;
            color: #2c3e50;
            border-bottom: 1px solid #e2e8f0;
            padding-bottom: 8px;
        }

        .status-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
        }

        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }

        .card-title {
            margin: 0;
            font-size: 1rem;
            font-weight: 600;
            color: #5a6a85;
        }

        .card-value {
            font-size: 2rem;
            font-weight: 700;
            margin: 10px 0;
            color: #2c3e50;
        }

        .card-subtext {
            font-size: 0.85rem;
            color: #64748b;
        }

        .healthy {
            color: #10b981;
        }

        .unhealthy {
            color: #ef4444;
        }

        .warning {
            color: #f59e0b;
        }

        .metric-chart {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
            height: 300px;
        }

        .metric-charts {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
        }

        @media (max-width: 768px) {
            .metric-charts {
                grid-template-columns: 1fr;
            }

            .status-cards {
                grid-template-columns: 1fr;
            }
        }

        .refresh-btn {
            background-color: #3b82f6;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 8px 16px;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .refresh-btn:hover {
            background-color: #2563eb;
        }

        .last-updated {
            color: #64748b;
            font-size: 0.9rem;
            margin-top: 5px;
            text-align: right;
        }

        .loading {
            opacity: 0.6;
        }

        select, button {
            padding: 8px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }

        /* 表格样式 */
        .data-table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }

        .data-table th {
            background-color: #f8fafc;
            font-weight: 600;
            color: #5a6a85;
        }

        .data-table tr:hover {
            background-color: #f8fafc;
        }

        /* 进度条样式 */
        .progress-container {
            background-color: #e2e8f0;
            border-radius: 4px;
            height: 8px;
            width: 100%;
            margin-top: 8px;
        }

        .progress-bar {
            height: 100%;
            border-radius: 4px;
            background-color: #3b82f6;
        }

        /* 响应时间分布图 */
        .response-time-distribution {
            display: flex;
            align-items: flex-end;
            height: 150px;
            margin-top: 15px;
            gap: 8px;
        }

        .time-bar {
            flex: 1;
            background-color: #3b82f6;
            min-width: 30px;
            position: relative;
            transition: height 0.3s;
        }

        .time-bar-label {
            position: absolute;
            bottom: -25px;
            left: 0;
            right: 0;
            text-align: center;
            font-size: 0.75rem;
            color: #64748b;
        }

        .time-bar-value {
            position: absolute;
            top: -25px;
            left: 0;
            right: 0;
            text-align: center;
            font-size: 0.75rem;
            color: #64748b;
        }

        /* 状态指示器 */
        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-healthy {
            background-color: #10b981;
        }

        .status-unhealthy {
            background-color: #ef4444;
        }

        .status-warning {
            background-color: #f59e0b;
        }

        /* 响应式布局 */
        @media (max-width: 500px) {
            .header {
                flex-direction: column;
                align-items: flex-start;
            }

            .refresh-controls {
                margin-top: 15px;
            }
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .form-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .btn-primary {
            background-color: #3b82f6;
            color: white;
        }

        .btn-danger {
            background-color: #ef4444;
            color: white;
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        #resultContent {
            background-color: #f8fafc;
            padding: 15px;
            border-radius: 4px;
            margin-top: 10px;
        }

        .result-metric {
            margin-bottom: 8px;
        }

        .metric-label {
            font-weight: bold;
            display: inline-block;
            width: 150px;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>数据库与系统监控仪表盘</h1>
        <div class="refresh-controls">
            <div class="refresh-interval">
                <label for="interval">刷新间隔:</label>
                <select id="interval">
                    <option value="5000">5秒</option>
                    <option value="10000" selected>10秒</option>
                    <option value="30000">30秒</option>
                    <option value="60000">1分钟</option>
                </select>
            </div>
            <button id="refreshBtn" class="refresh-btn">刷新数据</button>
        </div>
    </div>

    <div class="dashboard-section">
        <h2>压力测试</h2>
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">压力测试控制台</h3>
            </div>
            <div class="card-content">
                <div id="stressTestForm">
                    <div class="form-group">
                        <label for="duration">持续时间(秒):</label>
                        <input type="number" id="duration" min="1" max="600" value="30" class="form-input">
                    </div>
                    <div class="form-group">
                        <label for="concurrency">并发数:</label>
                        <input type="number" id="concurrency" min="1" max="1000" value="50" class="form-input">
                    </div>
                    <div class="form-group">
                        <label for="endpoint">测试端点:</label>
                        <input type="text" id="endpoint" value="/user/1" class="form-input">
                    </div>
                    <div class="form-actions">
                        <button id="startStressTest" class="btn btn-primary">开始测试</button>
                        <button id="stopStressTest" class="btn btn-danger" disabled>停止测试</button>
                    </div>
                </div>
                <div id="stressTestResult" style="margin-top: 20px; display: none;">
                    <h4>测试结果</h4>
                    <div id="resultContent"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- 系统状态概览部分 -->
    <div class="dashboard-section">
        <h2>系统状态概览</h2>
        <div class="status-cards">
            <div class="card" id="redisStatusCard">
                <div class="card-header">
                    <h3 class="card-title">Redis状态</h3>
                </div>
                <div class="card-value" id="redisStatus">加载中...</div>
                <div class="card-subtext">连接池: <span id="redisPoolSize">-</span> / 最小空闲: <span
                        id="redisMinIdleConns">-</span></div>
            </div>

            <div class="card" id="mysqlStatusCard">
                <div class="card-header">
                    <h3 class="card-title">MySQL状态</h3>
                </div>
                <div class="card-value" id="mysqlStatus">加载中...</div>
                <div class="card-subtext">最大连接: <span id="dbMaxOpenConns">-</span> / 最大空闲: <span
                        id="dbMaxIdleConns">-</span></div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">缓存命中率</h3>
                </div>
                <div class="card-value" id="cacheHitRate">加载中...</div>
                <div class="progress-container">
                    <div class="progress-bar" id="cacheHitRateBar" style="width: 0%"></div>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">数据库连接</h3>
                </div>
                <div class="card-value">
                    <span id="dbActiveConns">0</span> / <span id="dbIdleConns">0</span>
                </div>
                <div class="card-subtext">活跃 / 空闲</div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">当前请求</h3>
                </div>
                <div class="card-value" id="concurrentRequests">0</div>
                <div class="card-subtext">历史最大: <span id="maxConcurrentRequests">0</span></div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">每秒请求数</h3>
                </div>
                <div class="card-value" id="requestsPerSecond">0</div>
                <div class="card-subtext">最近一分钟平均: <span id="lastMinuteQPS">0</span></div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">平均响应时间</h3>
                </div>
                <div class="card-value" id="avgResponseTime">0</div>
                <div class="card-subtext">毫秒</div>
            </div>

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">运行时间</h3>
                </div>
                <div class="card-value" id="uptime">加载中...</div>
            </div>
        </div>
    </div>

    <!-- 请求响应监控部分 -->
    <div class="dashboard-section">
        <h2>请求响应监控</h2>
        <div class="metric-charts">
            <div class="metric-chart">
                <h3>QPS与响应时间历史</h3>
                <canvas id="performanceChart"></canvas>
            </div>
            <div class="metric-chart">
                <h3>响应时间分布</h3>
                <div class="response-time-distribution" id="responseTimeDistribution">
                    <!-- Response time bars will be dynamically generated -->
                </div>
            </div>
        </div>
    </div>

    <!-- 数据库性能监控部分 -->
    <div class="dashboard-section">
        <h2>数据库性能监控</h2>
        <div class="metric-charts">
            <div class="metric-chart">
                <h3>数据库连接池状态</h3>
                <canvas id="connectionChart"></canvas>
            </div>
            <div class="metric-chart">
                <h3>查询与错误统计</h3>
                <canvas id="queryChart"></canvas>
            </div>
        </div>
        <div class="status-cards">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">数据库查询</h3>
                </div>
                <div class="card-value" id="dbQueryCount">0</div>
            </div>
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">错误统计</h3>
                </div>
                <div class="card-value">
                    数据库: <span id="dbErrorCount">0</span><br>
                    Redis: <span id="redisErrorCount">0</span>
                </div>
            </div>
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">慢查询次数</h3>
                </div>
                <div class="card-value" id="slowQueryCount">0</div>
            </div>
        </div>
    </div>

    <!-- API端点分析 -->
    <div class="dashboard-section">
        <h2>API端点分析</h2>
        <table class="data-table" id="endpointTable">
            <thead>
            <tr>
                <th>端点</th>
                <th>请求数</th>
                <th>占比</th>
            </tr>
            </thead>
            <tbody>
            <!-- Rows will be dynamically generated -->
            </tbody>
        </table>
    </div>

    <!-- HTTP状态码统计 -->
    <div class="dashboard-section">
        <h2>HTTP状态码分布</h2>
        <div class="status-cards" id="httpStatusCards">
            <!-- HTTP status cards will be dynamically generated -->
        </div>
    </div>

    <div class="last-updated" id="lastUpdated"></div>
</div>
</body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<script>
    // 存储历史数据用于图表
    const historyData = {
        timestamps: [],
        activeConnections: [],
        idleConnections: [],
        queries: [],
        dbErrors: [],
        redisErrors: [],
        slowQueries: [],
        qps: [],
        responseTime: [],
        concurrentRequests: []
    };

    // 最大历史数据点数
    const MAX_HISTORY_POINTS = 20;

    // 图表对象
    let connectionChart;
    let queryChart;
    let performanceChart;

    // 响应时间桶标签
    const responseTimeBucketLabels = [
        "0-10ms", "10-50ms", "50-100ms", "100-500ms", "500-1000ms", ">1000ms"
    ];

    // 初始化图表
    function initCharts() {
        // 连接池状态图表
        const connectionCtx = document.getElementById('connectionChart').getContext('2d');
        connectionChart = new Chart(connectionCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        label: '活跃连接',
                        data: [],
                        borderColor: '#3b82f6',
                        backgroundColor: 'rgba(59, 130, 246, 0.1)',
                        tension: 0.3,
                        fill: true
                    },
                    {
                        label: '空闲连接',
                        data: [],
                        borderColor: '#10b981',
                        backgroundColor: 'rgba(16, 185, 129, 0.1)',
                        tension: 0.3,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '数据库连接池监控'
                    }
                }
            }
        });

        // 查询与错误图表
        const queryCtx = document.getElementById('queryChart').getContext('2d');
        queryChart = new Chart(queryCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        label: '查询总数',
                        data: [],
                        borderColor: '#6366f1',
                        tension: 0.3,
                        yAxisID: 'y'
                    },
                    {
                        label: '数据库错误',
                        data: [],
                        borderColor: '#ef4444',
                        tension: 0.3,
                        yAxisID: 'y1'
                    },
                    {
                        label: 'Redis错误',
                        data: [],
                        borderColor: '#f59e0b',
                        tension: 0.3,
                        yAxisID: 'y1'
                    },
                    {
                        label: '慢查询',
                        data: [],
                        borderColor: '#8b5cf6',
                        tension: 0.3,
                        yAxisID: 'y1'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '查询总数'
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        beginAtZero: true,
                        grid: {
                            drawOnChartArea: false,
                        },
                        title: {
                            display: true,
                            text: '错误数'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '查询与错误监控'
                    }
                }
            }
        });

        // 性能监控图表
        const performanceCtx = document.getElementById('performanceChart').getContext('2d');
        performanceChart = new Chart(performanceCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        label: 'QPS',
                        data: [],
                        borderColor: '#3b82f6',
                        tension: 0.3,
                        yAxisID: 'y'
                    },
                    {
                        label: '响应时间(ms)',
                        data: [],
                        borderColor: '#f59e0b',
                        tension: 0.3,
                        yAxisID: 'y1'
                    },
                    {
                        label: '并发请求数',
                        data: [],
                        borderColor: '#8b5cf6',
                        tension: 0.3,
                        yAxisID: 'y'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '请求/并发数'
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        beginAtZero: true,
                        grid: {
                            drawOnChartArea: false,
                        },
                        title: {
                            display: true,
                            text: '响应时间(ms)'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '系统性能监控'
                    }
                }
            }
        });
    }

    // 更新图表数据
    function updateCharts() {
        // 更新连接图表
        connectionChart.data.labels = historyData.timestamps;
        connectionChart.data.datasets[0].data = historyData.activeConnections;
        connectionChart.data.datasets[1].data = historyData.idleConnections;
        connectionChart.update();

        // 更新查询图表
        queryChart.data.labels = historyData.timestamps;
        queryChart.data.datasets[0].data = historyData.queries;
        queryChart.data.datasets[1].data = historyData.dbErrors;
        queryChart.data.datasets[2].data = historyData.redisErrors;
        queryChart.data.datasets[3].data = historyData.slowQueries;
        queryChart.update();

        // 更新性能图表
        performanceChart.data.labels = historyData.timestamps;
        performanceChart.data.datasets[0].data = historyData.qps;
        performanceChart.data.datasets[1].data = historyData.responseTime;
        performanceChart.data.datasets[2].data = historyData.concurrentRequests;
        performanceChart.update();
    }

    // 添加历史数据点
    function addHistoryDataPoint(metrics) {
        const now = new Date();
        const timeLabel = now.getHours().toString().padStart(2, '0') + ':' +
            now.getMinutes().toString().padStart(2, '0') + ':' +
            now.getSeconds().toString().padStart(2, '0');

        historyData.timestamps.push(timeLabel);
        historyData.activeConnections.push(metrics.db_active_conns);
        historyData.idleConnections.push(metrics.db_idle_conns);
        historyData.queries.push(metrics.db_query_count);
        historyData.dbErrors.push(metrics.db_error_count);
        historyData.redisErrors.push(metrics.redis_error_count);
        historyData.slowQueries.push(metrics.slow_query_count);
        historyData.qps.push(metrics.requests_per_second);
        historyData.responseTime.push(metrics.avg_response_time);
        historyData.concurrentRequests.push(metrics.concurrent_requests);

        // 限制历史数据点数量
        if (historyData.timestamps.length > MAX_HISTORY_POINTS) {
            historyData.timestamps.shift();
            historyData.activeConnections.shift();
            historyData.idleConnections.shift();
            historyData.queries.shift();
            historyData.dbErrors.shift();
            historyData.redisErrors.shift();
            historyData.slowQueries.shift();
            historyData.qps.shift();
            historyData.responseTime.shift();
            historyData.concurrentRequests.shift();
        }
    }

    // 更新响应时间分布图
    function updateResponseTimeDistribution(buckets) {
        const container = document.getElementById('responseTimeDistribution');
        container.innerHTML = '';

        // 找出最大值以便缩放
        const maxValue = Math.max(...buckets);

        // 为每个时间桶创建一个可视化条形
        buckets.forEach((value, index) => {
            const percentage = maxValue > 0 ? (value / maxValue * 100) : 0;
            const bar = document.createElement('div');
            bar.className = 'time-bar';
            bar.style.height = `${percentage}%`;

            const label = document.createElement('div');
            label.className = 'time-bar-label';
            label.textContent = responseTimeBucketLabels[index];

            const valueDisplay = document.createElement('div');
            valueDisplay.className = 'time-bar-value';
            valueDisplay.textContent = value;

            bar.appendChild(label);
            bar.appendChild(valueDisplay);
            container.appendChild(bar);
        });
    }

    // 更新端点分析表格
    function updateEndpointTable(endpointStats) {
        const table = document.getElementById('endpointTable').getElementsByTagName('tbody')[0];
        table.innerHTML = '';

        // 计算总请求数
        let totalRequests = 0;
        for (const endpoint in endpointStats) {
            totalRequests += endpointStats[endpoint];
        }

        // 按请求数降序排序端点
        const sortedEndpoints = Object.entries(endpointStats)
            .sort((a, b) => b[1] - a[1]);

        // 生成表格行
        sortedEndpoints.forEach(([endpoint, count]) => {
            const percentage = ((count / totalRequests) * 100).toFixed(2);
            const row = table.insertRow();

            const endpointCell = row.insertCell(0);
            endpointCell.textContent = endpoint;

            const countCell = row.insertCell(1);
            countCell.textContent = count;

            const percentageCell = row.insertCell(2);
            percentageCell.textContent = `${percentage}%`;
        });
    }

    // 更新HTTP状态码统计
    function updateStatusCodes(statusCodeStats) {
        const container = document.getElementById('httpStatusCards');

        if (!container) {
            console.warn('HTTP status codes container not found in the DOM');
            return;
        }

        container.innerHTML = '';

        // 为每个状态码创建一个卡片
        for (const [code, count] of Object.entries(statusCodeStats)) {
            // 确定状态码类型和颜色
            let statusClass = '';
            if (code.startsWith('2')) {
                statusClass = 'healthy';
            } else if (code.startsWith('4')) {
                statusClass = 'warning';
            } else if (code.startsWith('5')) {
                statusClass = 'unhealthy';
            }

            const card = document.createElement('div');
            card.className = 'card';
            card.innerHTML = `
            <div class="card-header">
                <h3 class="card-title">状态 ${code}</h3>
                <span class="status-indicator status-${statusClass}"></span>
            </div>
            <div class="card-value ${statusClass}">${count}</div>
            <div class="card-subtext">请求数</div>
        `;

            container.appendChild(card);
        }
    }

    // 获取并更新指标数据
    async function fetchMetrics() {
        const cards = document.querySelectorAll('.card');
        cards.forEach(card => card.classList.add('loading'));

        try {
            const response = await fetch('/metrics');
            const data = await response.json();

            // 更新数据库状态卡片
            document.getElementById('redisStatus').textContent = data.redis_status;
            document.getElementById('redisStatus').className = 'card-value ' + data.redis_status.toLowerCase();
            document.getElementById('redisPoolSize').textContent = data.redis_pool_size;
            document.getElementById('redisMinIdleConns').textContent = data.redis_min_idle_conns;

            document.getElementById('mysqlStatus').textContent = data.mysql_status;
            document.getElementById('mysqlStatus').className = 'card-value ' + data.mysql_status.toLowerCase();
            document.getElementById('dbMaxOpenConns').textContent = data.db_max_open_conns;
            document.getElementById('dbMaxIdleConns').textContent = data.db_max_idle_conns;

            // 更新缓存命中率
            document.getElementById('cacheHitRate').textContent = data.cache_hit_rate.toFixed(2) + '%';
            document.getElementById('cacheHitRateBar').style.width = data.cache_hit_rate + '%';

            // 更新数据库连接
            document.getElementById('dbActiveConns').textContent = data.db_active_conns;
            document.getElementById('dbIdleConns').textContent = data.db_idle_conns;

            // 更新请求相关指标
            document.getElementById('concurrentRequests').textContent = data.concurrent_requests;
            document.getElementById('maxConcurrentRequests').textContent = data.max_concurrent_requests;
            document.getElementById('requestsPerSecond').textContent = data.requests_per_second.toFixed(2);
            document.getElementById('lastMinuteQPS').textContent = data.last_minute_qps.toFixed(2);
            document.getElementById('avgResponseTime').textContent = data.avg_response_time.toFixed(2);

            // 更新运行时间
            document.getElementById('uptime').textContent = data.uptime;

            // 更新数据库性能指标
            document.getElementById('dbQueryCount').textContent = data.db_query_count;
            document.getElementById('dbErrorCount').textContent = data.db_error_count;
            document.getElementById('redisErrorCount').textContent = data.redis_error_count;
            document.getElementById('slowQueryCount').textContent = data.slow_query_count;

            // 更新响应时间分布
            updateResponseTimeDistribution(data.response_time_buckets);

            // 更新端点分析表
            updateEndpointTable(data.endpoint_stats);

            // 更新HTTP状态码统计
            updateStatusCodes(data.status_code_stats);

            // 添加数据点到历史数据中
            addHistoryDataPoint(data);

            // 更新图表
            updateCharts();

            // 更新最后更新时间
            document.getElementById('lastUpdated').textContent = '最后更新: ' + new Date().toLocaleTimeString();
        } catch (error) {
            console.error('获取指标数据失败:', error);
        } finally {
            cards.forEach(card => card.classList.remove('loading'));
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', function () {
        // 初始化图表
        initCharts();

        // 首次加载数据
        fetchMetrics();

        // 设置定时刷新
        const intervalSelect = document.getElementById('interval');
        let refreshInterval;

        function startRefreshTimer() {
            const interval = parseInt(intervalSelect.value);
            if (refreshInterval) {
                clearInterval(refreshInterval);
            }
            refreshInterval = setInterval(fetchMetrics, interval);
        }

        // 监听刷新间隔变化
        intervalSelect.addEventListener('change', startRefreshTimer);

        // 监听刷新按钮点击
        document.getElementById('refreshBtn').addEventListener('click', fetchMetrics);

        // 启动定时刷新
        startRefreshTimer();
    });



    // 压力测试控制
    document.addEventListener('DOMContentLoaded', function() {
        const startBtn = document.getElementById('startStressTest');
        const stopBtn = document.getElementById('stopStressTest');
        const resultDiv = document.getElementById('stressTestResult');

        // 检查压力测试状态
        function checkStressTestStatus() {
            fetch('/stress/status')
                .then(response => response.json())
                .then(data => {
                    if (data.running) {
                        startBtn.disabled = true;
                        stopBtn.disabled = false;
                        // 如果是运行中，可以定期获取结果
                        const resultCheckInterval = setInterval(() => {
                            fetch('/stress/status').then(statusData => {
                                if (!statusData.running) {
                                    clearInterval(resultCheckInterval);
                                    fetchStressTestResult(); // 获取最终结果
                                }
                            });
                        }, 1000);
                    } else {
                        startBtn.disabled = false;
                        stopBtn.disabled = true;
                        fetchStressTestResult(); // 直接获取结果
                    }
                });
        }

        // 启动压力测试
        startBtn.addEventListener('click', function() {
            const duration = parseInt(document.getElementById('duration').value);
            const concurrency = parseInt(document.getElementById('concurrency').value);
            const endpoint = document.getElementById('endpoint').value;

            if (isNaN(duration) || isNaN(concurrency) || !endpoint) {
                alert('请填写所有字段');
                return;
            }

            fetch('/stress/start', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    duration: duration,
                    concurrency: concurrency,
                    endpoint: endpoint
                })
            })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    startBtn.disabled = true;
                    stopBtn.disabled = false;
                    resultDiv.style.display = 'none';

                    // 定期检查状态
                    const checkInterval = setInterval(() => {
                        fetch('/stress/status')
                            .then(response => response.json())
                            .then(data => {
                                if (!data.running) {
                                    clearInterval(checkInterval);
                                    checkStressTestStatus();
                                    // 获取最终结果
                                    // 这里可以添加获取结果的逻辑
                                }
                            });
                    }, 1000);
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('启动压力测试失败');
                });
        });

        // 停止压力测试
        stopBtn.addEventListener('click', function() {
            fetch('/stress/stop', {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    alert(data.message);
                    checkStressTestStatus();
                })
                .then(() => fetchStressTestResult()) // 停止后获取结果
                .then(() => checkStressTestStatus())
                .catch(error => {
                    console.error('Error:', error);
                    alert('停止压力测试失败');
                });
        });

        // 初始化检查状态
        checkStressTestStatus();

        // 添加获取测试结果的函数
        async function fetchStressTestResult() {
            try {
                const response = await fetch('/stress/result');
                if (!response.ok) throw new Error('暂无测试结果');
                const data = await response.json();
                displayResult(data);
            } catch (error) {
                console.error('获取测试结果失败:', error);
            }
        }

        // 显示结果的函数
        function displayResult(result) {
            let html = `
                <div class="result-metric"><span class="metric-label">总请求数:</span> ${result.total_requests}</div>
                <div class="result-metric"><span class="metric-label">成功请求:</span> ${result.success_count}</div>
                <div class="result-metric"><span class="metric-label">失败请求:</span> ${result.error_count}</div>
                <div class="result-metric"><span class="metric-label">平均响应时间:</span> ${result.avg_response_time.toFixed(2)} ms</div>
                <div class="result-metric"><span class="metric-label">最小响应时间:</span> ${result.min_response_time.toFixed(2)} ms</div>
                <div class="result-metric"><span class="metric-label">最大响应时间:</span> ${result.max_response_time.toFixed(2)} ms</div>
                <div class="result-metric"><span class="metric-label">请求/秒:</span> ${result.requests_per_sec.toFixed(2)}</div>
                <div class="result-metric"><span class="metric-label">状态码分布:</span></div>
                <ul>
            `;

            for (const [code, count] of Object.entries(result.status_code_dist)) {
                html += `<li>HTTP ${code}: ${count} 次</li>`;
            }

            html += `</ul>`;

            document.getElementById('resultContent').innerHTML = html;
            resultDiv.style.display = 'block';
        }
    });


</script>